// This openscad script generates a half sphere transition
// between a larger and a smaller pipe

// Resolution of 3D model
$fn=40;
// Thickness of the walls [mm]
wall=3;

/*[ Pipe with larger outer diameter ]*/
// Length of larger pipe without transition [mm]
largePartLen=40;
// Outer diameter of larger pipe [mm]
largePartDia=50.2;

/*[ Pipe with smaller outer diameter ]*/
// Length of smaller pipe without transition [mm]
smallPartLen=20;
// Outer diameter of smaller pipe [mm]
smallPartDia=20.0;

/*[ Hidden ]*/

// Distance between larger and smaller pipe: This is the transition length
//a^2 + b^2 = c^2
//c=r=largePartDia/2
//a=smallPartDia/2
//b=?
//b^2 = c^2 - a^2
//    _____________________________________________
//b= V ((largePartDia/2)^2-(smallPartDia/2)^2)
transitionDistance = sqrt((largePartDia/2)^2-(smallPartDia/2)^2);
echo("transitionDistance = ", transitionDistance);


///////////////////////////////////////////////////////////////////////////////////
// main
///////////////////////////////////////////////////////////////////////////////////
difference()
{
    makeOuterForm();
    makeInnerForm();
}

///////////////////////////////////////////////////////////////////////////////////
// make the outer hull
///////////////////////////////////////////////////////////////////////////////////
module makeOuterForm()
{
    union()
    {
        // make larger part
        translate([0, 0, transitionDistance]) 
            cylinder(h=largePartLen, d=largePartDia);
        // make transition between larger and smaller part
        translate([0, 0, transitionDistance]) 
            sphere(d=largePartDia);
        // make smaller part
        translate([0,0,-smallPartLen])
            cylinder(h=smallPartLen, d=smallPartDia);
    }
}
///////////////////////////////////////////////////////////////////////////////////
// make the inner hull
///////////////////////////////////////////////////////////////////////////////////
module makeInnerForm()
{
        union()
        {
            // make larger part
            translate([0, 0, transitionDistance]) 
                cylinder(h=largePartLen+wall+0.1, d=largePartDia-2*wall);
            // make transition between larger and smaller part
            translate([0, 0, transitionDistance]) 
                sphere(d=largePartDia-2*wall);
            // make smaller part
            translate([0,0,-smallPartLen-0.1])
                cylinder(h=smallPartLen+wall+0.2, d=smallPartDia-2*wall);
        }
}